﻿using LD.Tool;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Linq;

namespace LD.Host
{
    internal partial class ToolItemCollection : Panel
    {
        //鼠标按下坐标（control控件的相对坐标）
        private Point _mouseDownPoint = Point.Empty;
        //显示拖动效果的矩形
        private Rectangle rect = Rectangle.Empty;
        private ContextMenuStrip contextMenuStrip1;
        private ToolStripMenuItem tsm_Run;
        private ToolStripMenuItem tsm_delete;
        private ToolStripMenuItem tsm_property;
        private ToolStripMenuItem tsm_enabled;
        private ToolStripMenuItem tsm_copy;
        private ToolStripSeparator sparator1;
        private ToolStripSeparator sparator2;
        //是否正在拖拽
        private bool isDrag = false;
        //拖动后滚动条的位置
        private Point CurrentPoint;
        //拖动后的位置（相对控件而已）
        private Point CurrentPointByThis;
        //当前
        public ToolItemCollection()
        {
            this.AllowDrop = true;
            this.AutoScroll = true;

            //右击菜单
            sparator1 = new ToolStripSeparator();
            sparator2 = new ToolStripSeparator();
            contextMenuStrip1 = new ContextMenuStrip();
            tsm_Run = new ToolStripMenuItem();
            tsm_Run.Font = new Font("宋体", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            tsm_Run.Text = "运行";
            tsm_Run.Margin = new Padding(0, 5, 0, 5);

            tsm_delete = new ToolStripMenuItem();
            tsm_delete.Text = "删除";
            tsm_delete.Margin = new Padding(0, 5, 0, 5);
            tsm_delete.Font = new Font("宋体", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));

            tsm_property = new ToolStripMenuItem();
            tsm_property.Text = "属性";
            tsm_property.Margin = new Padding(0, 5, 0, 5);
            tsm_property.Font = new Font("宋体", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));

            tsm_enabled = new ToolStripMenuItem();
            tsm_enabled.Text = "禁用";
            tsm_enabled.Margin = new Padding(0, 5, 0, 5);
            tsm_enabled.Font = new Font("宋体", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));

            tsm_copy = new ToolStripMenuItem();
            tsm_copy.Text = "复制";
            tsm_copy.Margin = new Padding(0, 5, 0, 5);
            tsm_copy.Font = new Font("宋体", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            tsm_copy.Visible = true;

            tsm_property.Click += Tsm_property_Click;
            tsm_Run.Click += Tsm_Run_Click;
            tsm_delete.Click += Tsm_delete_Click;
            tsm_enabled.Click += Tsm_enabled_Click;
            tsm_copy.Click += Tsm_copy_Click;

            contextMenuStrip1.Items.Add(tsm_Run);
            contextMenuStrip1.Items.Add(tsm_delete);
            contextMenuStrip1.Items.Add(tsm_enabled);
            contextMenuStrip1.Items.Add(sparator1);

            contextMenuStrip1.Items.Add(tsm_copy);
            contextMenuStrip1.Items.Add(sparator2);
            contextMenuStrip1.Items.Add(tsm_property);

            contextMenuStrip1.Opening += ContextMenuStrip1_Opening;

        }
        private void Tsm_copy_Click(object sender, EventArgs e)
        {
            ToolItem jobItem = (ToolItem)((sender as ToolStripMenuItem).GetCurrentParent() as ContextMenuStrip).SourceControl;
            Clipboard.SetData("ld", Newtonsoft.Json.JsonConvert.SerializeObject(jobItem.Tool));
        }
        private void Tsm_enabled_Click(object sender, EventArgs e)
        {
            ToolItem jobItem = (ToolItem)((sender as ToolStripMenuItem).GetCurrentParent() as ContextMenuStrip).SourceControl;
            jobItem.IsEnabled = !jobItem.IsEnabled;
        }
        private void ContextMenuStrip1_Opening(object sender, System.ComponentModel.CancelEventArgs e)
        {
            var item = (sender as ContextMenuStrip).SourceControl;// as ContextMenuStrip;
            ToolItem jobItem = (ToolItem)item;
            if (!jobItem.IsEnabled)
                tsm_enabled.Text = "启用";
            else
                tsm_enabled.Text = "禁用";
        }
        public void SaveTool()
        {
            //delete

            //save

        }
        private void Tsm_property_Click(object sender, EventArgs e)
        {
            ToolItem toolItem = (ToolItem)((sender as ToolStripMenuItem).GetCurrentParent() as ContextMenuStrip).SourceControl;
            var frmParam = FlowHelper.OpenFrmParam(toolItem.Tool);

            if (frmParam != null)
            {
                frmParam.TB_Tool = toolItem.Tool;
                if (frmParam.ShowDialog() == DialogResult.OK)
                {
                    toolItem.Tool = frmParam.TB_Tool;
                }
                //控件刷新
                toolItem.Refresh();
            }
        }

        private void Tsm_delete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("你确定要删除工具吗？", "警告", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
            {
                ToolItem toolItem = (ToolItem)((sender as ToolStripMenuItem).GetCurrentParent() as ContextMenuStrip).SourceControl;
                this.Controls.Remove(toolItem);
                ToolItems.Remove(toolItem);
            }
        }

        private void Tsm_Run_Click(object sender, EventArgs e)
        {
            ToolItem jobItem = (ToolItem)((sender as ToolStripMenuItem).GetCurrentParent() as ContextMenuStrip).SourceControl;
            jobItem.Execute();
        }
        public List<ToolItem> ToolItems { get; set; } = new List<ToolItem>();
        protected override void OnDragEnter(DragEventArgs drgevent)
        {
            base.OnDragEnter(drgevent);
            drgevent.Effect = DragDropEffects.Move;

        }
        protected override void OnDragDrop(DragEventArgs drgevent)
        {
            base.OnDragDrop(drgevent);
            try
            {
                Point point = new Point(drgevent.X, drgevent.Y);

                var flowName = this.Parent.Text;
                var _tool = (TB_Tool)drgevent.Data.GetData(typeof(TB_Tool));
                TB_Tool tool = new TB_Tool()
                {
                    ClassName = _tool.ClassName,
                    FlowName = flowName,
                    FrmParam = _tool.FrmParam,
                    Id = _tool.Id,
                    Name = _tool.Name,
                    Param = _tool.Param,
                    Sort = _tool.Sort,
                    Text = _tool.Text,
                    ToolType = _tool.ToolType,
                };

                //弹出属性窗口
                var frmParam = FlowHelper.OpenFrmParam(tool);

                if (frmParam != null)
                {
                    frmParam.TB_Tool = tool;
                    if (frmParam.ShowDialog() == DialogResult.OK)
                    {
                        ToolItem toolItem = GetJobItem(frmParam.TB_Tool);
                        //toolItem.Location = rect.Location;
                        toolItem.Location = this.PointToClient(point);
                        ToolItems.Add(toolItem);
                        ControlRefresh();
                    }
                }
                else
                {
                    ToolItem toolItem = GetJobItem(tool);

                    //toolItem.Location = rect.Location;
                    toolItem.Location = this.PointToClient(point);
                    ToolItems.Add(toolItem);
                    ControlRefresh();
                }
            }
            catch (Exception)
            {
            }
        }
        public void AddTool(TB_Tool toolParam)
        {
            if (toolParam == null) return;
            var drgevent = Control.MousePosition;
            Point point = new Point(drgevent.X, drgevent.Y);
            var item = GetJobItem(toolParam);
            item.Tool = toolParam;
            item.Location = this.PointToClient(point);
            ToolItems.Add(item);
            ControlRefresh();
        }
        private void JobItem_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isDrag = true;
                //重新设置rect的位置，跟随鼠标移动
                rect.Location = getPointToForm((sender as ToolItem), new Point(e.Location.X - _mouseDownPoint.X, e.Location.Y - _mouseDownPoint.Y));
                //CurrentPointByThis = new Point(e.Location.X, e.Location.Y);
                //Console.WriteLine(CurrentPointByThis);
                this.Refresh();
            }
        }

        private void JobItem_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _mouseDownPoint = e.Location;
                //记录控件的大小
                rect = (sender as ToolItem).Bounds;
            }
        }


        private void JobItem_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (isDrag)
                {
                    isDrag = false;
                    //获取this中
                    //移动control到放开鼠标的地方
                    ToolItem jobItem = (sender as ToolItem);
                    jobItem.Location = rect.Location;
                    jobItem.Tool.X = jobItem.Location.X;
                    jobItem.Tool.Y = jobItem.Location.Y;
                    int index = rect.Location.Y / (jobItem.Height);
                    //this.Controls.SetChildIndex(jobItem, index);
                    //ReLoad();
                    this.Refresh();
                }
                reset();
            }
        }
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            if (rect != Rectangle.Empty)
            {
                if (isDrag)
                {//画一个和Control一样大小的黑框
                    e.Graphics.DrawRectangle(Pens.Red, rect);
                }
                else
                {
                    e.Graphics.DrawRectangle(new Pen(this.BackColor), rect);
                }
            }
        }
        //把相对与control控件的坐标，转换成相对于窗体的坐标。
        private Point getPointToForm(ToolItem toolItem, Point p)
        {
            return this.PointToClient(toolItem.PointToScreen(p));
        }



        #region 方法
        public List<TB_Tool> Tools
        {
            get
            {
                List<TB_Tool> tools = new List<TB_Tool>();
                foreach (var item in ToolItems)
                {
                    tools.Add(item.Tool);
                }
                return tools;
            }
            set
            {
                foreach (var item in value)
                {
                    ToolItem toolItem = GetJobItem(item);
                    ToolItems.Add(toolItem);
                }
                ControlRefresh();
            }
        }
        public ToolItem GetJobItem(TB_Tool model)
        {
            ToolItem toolItem = new ToolItem(model);
            toolItem.ContextMenuStrip = contextMenuStrip1;
            //toolItem.MouseDoubleClick += Tsm_property_Click;
            toolItem.Margin = new Padding(5, 5, 5, 5);
            toolItem.Width = 260;
            toolItem.Height = 60;
            toolItem.Location = new Point(model.X, model.Y);
            toolItem.ExecuteTime = 0;
            toolItem.MouseDown += JobItem_MouseDown;
            toolItem.MouseMove += JobItem_MouseMove;
            toolItem.MouseUp += JobItem_MouseUp;
            toolItem.BorderStyle = BorderStyle.FixedSingle;
            toolItem.Tool = model;
            return toolItem;
        }

        public void ToolCollectFormat()
        {
            //CurrentPoint = this.AutoScrollPosition;
            this.AutoScrollPosition = new Point(0, 0);
            int x = 10;
            int y = 10;
            int z = 5;
            ToolItems.Clear();
            //控件排序
            var tools = new List<ToolItem>();
            foreach (var item in this.Controls)
            {
                if (item.GetType() == typeof(ToolItem))
                {
                    tools.Add(item as ToolItem);
                }
            }
            tools = tools.OrderBy(p => p.Location.Y).ToList();
            foreach (var item in tools)
            {
                var tool = item as ToolItem;
                tool.Parent = this;
                tool.Location = new Point(x, y);
                tool.Tool.X = x;
                tool.Tool.Y = y;
                ToolItems.Add(tool);

                //计算下一个位置
                y += z + tool.Height;
            }
            //foreach (var item in this.Controls)
            //{
            //    if (item.GetType() == typeof(ToolItem))
            //    {
            //        var tool = item as ToolItem;
            //        tool.Parent = this;
            //        tool.Location = new Point(x, y);
            //        ToolItems.Add(tool);

            //        //计算下一个位置
            //        y += tool.Height;
            //    }
            //}
            //this.AutoScrollPosition = CurrentPoint;
        }
        //重置变量
        private void reset()
        {
            _mouseDownPoint = Point.Empty;
            rect = Rectangle.Empty;
            isDrag = false;
        }
        public void ControlRefresh()
        {
            this.Controls.Clear();
            foreach (var item in ToolItems)
            {
                this.Controls.Add(item);
            }

            //ReLoad();
        }
        #endregion
    }
}
